sample source
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server_2 {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8000);
System.out.println("server : " + server);
// 10번만 클라이언트 소켓을 받아들임
for (int i = 0; i < 10; i++) {
Socket client = server.accept();
System.out.println(client);
// Input
InputStream in = client.getInputStream();
Scanner inScanner = new Scanner(in);
String line = inScanner.nextLine();
System.out.println(line);
// Output
String msg = "<h1>Hello World</h1>";
OutputStream out = client.getOutputStream();
// 헤더정보 포함
out.write(new String("HTTP/1.1 200 OK\r\n").getBytes());
out.write(new String("Cache-Control: private\r\n").getBytes());
out.write(new String("Content-Length: " + msg.getBytes().length
+ "\r\n").getBytes());
out.write(new String(
"Content-Type: text/html; charset=UTF-8\r\n\r\n")
.getBytes());
out.write(msg.getBytes());
out.flush();
out.close();
if (client != null) {
client.close(); // 소켓 close
}
}
server.close(); // 서버 소켓도 close
}
}
<?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:id="@+id/page01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID :"/>
<EditText
android:id="@+id/edit_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PWord : "/>
<EditText
android:id="@+id/edit_pword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NickName :"/>
<EditText
android:id="@+id/edit_nick"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Self Introduce : "/>
<EditText
android:id="@+id/edit_subject"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="4"/>
</TableRow>
<View
android:layout_height="2dip"
android:background="#AAAAAA"/>
<TableRow>
<Button
android:text="Send"
android:id="@+id/button_submit"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
<LinearLayout
android:id="@+id/page02"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
sample source
package com.example.test07;
import java.util.ArrayList;
import android.app.TabActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
public class MainActivity extends TabActivity {
// 전역변수 선언
TabHost mTabHost = null;
String myId, myPWord, myNick, mySubject, myResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Tab 만들기
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_1").setIndicator("request Server")
.setContent(R.id.page01));
mTabHost.addTab(mTabHost.newTabSpec("tab_2").setIndicator("response Server")
.setContent(R.id.page02));
findViewById(R.id.button_submit).setOnClickListener(buttonClick);
}
// ------------------------------
// button Click
// ------------------------------
Button.OnClickListener buttonClick = new Button.OnClickListener() {
public void onClick(View v) {
// 사용자가 입력한 내용을 전역변수에 저장한다
myId = ((EditText) (findViewById(R.id.edit_id))).getText()
.toString();
myPWord = ((EditText) (findViewById(R.id.edit_pword))).getText()
.toString();
myNick = ((EditText) (findViewById(R.id.edit_nick))).getText()
.toString();
mySubject = ((EditText) (findViewById(R.id.edit_subject)))
.getText().toString();
PostData();
}
};
// ------------------------------
// 웹서버로 데이터 전송
// ------------------------------
public void PostData() {
// Server URL (필자의 개인 서버 주소임)
String Server_URL = "http://www.google.co.kr";
// 전송할 데이터를 저장할 ArrayList 생성
ArrayList<HttpQue> sBuffer = new ArrayList<HttpQue>();
// ArrayList에 <변수=값> 형태로 저장
sBuffer.add(new HttpQue("", Server_URL)); // 서버 URL
sBuffer.add(new HttpQue("user_id", myId)); // "" 안의 문자열은
sBuffer.add(new HttpQue("user_pword", myPWord)); // 서버에 설정된 변수명이다
sBuffer.add(new HttpQue("user_nick", myNick));
sBuffer.add(new HttpQue("user_subject", mySubject));
// HttpPost 생성
HttpPosts mHttp = new HttpPosts(sBuffer);
android.util.Log.e("TDD", "START");
// Data 전송
mHttp.HttpPostData2();
myResult = mHttp.rString; // 전송 결과
android.util.Log.e("TDD", "END");
// Tab2에 있는 TextEdit에 전송 결과 표시
((TextView) (findViewById(R.id.text_result))).setText(myResult);
} // PostData
} // Activity
sample source
package com.example.test07;
//--------------------------
//HttpQue
//--------------------------
class HttpQue {
public String var; // 변수명
public String value; // 값
public HttpQue(String _var, String _value) { // 생성자
var = _var;
value = _value;
}
}
sample source
package com.example.test07;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;
//--------------------------
//HttpPost
//--------------------------
class HttpPosts {
public String rString; // receive String
public StringBuilder rBuffer;
private ArrayList<HttpQue> sBuffer; // sendBuffer
// --------------------------
// Constructor
// --------------------------
public HttpPosts(ArrayList<HttpQue> _sBuffer) {
sBuffer = _sBuffer;
rBuffer = new StringBuilder(200000); // receive 버퍼
rString = ""; // receive 스트링
}
private class ProcessFacebookTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
String postURL = sBuffer.get(0).value;
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
android.util.Log.e("TDD", sBuffer.get(0).value);
for (int i = 1; i < sBuffer.size(); i++) {
params.add(new BasicNameValuePair(sBuffer.get(i).var, sBuffer
.get(i).value));
android.util.Log.e("TDD",
sBuffer.get(i).var + "=" + sBuffer.get(i).value + "&");
}
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
HTTP.UTF_8);
android.util.Log.e("TDD", "3333333333333333333333");
post.setEntity(ent);
android.util.Log.e("TDD", "4444444444444444444444444");
HttpResponse responsePOST = client.execute(post);
android.util.Log.e("TDD", "55555555555555555555");
android.util.Log.e("TDD", responsePOST.toString());
HttpEntity resEntity = responsePOST.getEntity();
String test = "";
if (resEntity != null) {
test = test + EntityUtils.toString(resEntity);
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
rString = test;
android.util.Log.e("TDD", rString);
} catch (MalformedURLException e) {
android.util.Log.e("TDD", "MalformedURLException " + e.toString());
rString = "N/A";
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
// --------------------------
// URL 설정하고 접속하기
// --------------------------
public void HttpPostData2() {
new ProcessFacebookTask().execute(null,null,null);
} //
} // class
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
원하는 형태로 동작하는 브라우저를 만들 경우 사용됨
단순히 HTML을 렌더링 하는 역할을 담당
sample source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
sample source
package com.example.test09;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) this.findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true); //스크립트 사용여부
wv.getSettings().setBuiltInZoomControls(true); //줌컴트롤 사용여부
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //자바스크립트 새창열기 기능
wv.getSettings().setLightTouchEnabled(true);
wv.getSettings().setSavePassword(true); //폼데이터 패스워드 저장여부 설정
wv.getSettings().setSaveFormData(true); //폼데이터 저장 여부 설정
wv.setWebViewClient(new MyWebViewClient());
wv.loadUrl("/");
}
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
};
sample source
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setProgressBarIndeterminateVisibility(true);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setProgressBarIndeterminateVisibility(false);
}
jsalert.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>alert</title>
</head>
<body>
<h2>
<a href="javascript:alert('alertMessage.');">showMsg</a>
</h2>
</body>
</html>
sample source
Button btn = (Button)this.findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyWebChromeClient myWebChromeClient = new MyWebChromeClient();
wv.setWebChromeClient(myWebChromeClient);
wv.loadUrl("file:///android_asset/jsalert.html");
}
});
private class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
result.confirm();
return true;
}
}
WIFI or 4G 가 연결되어 있어야함.
네트워크로 처리하는 코드를 활용하기전에 연결상태를 확인해야함
이를 위해서 ConnectivityManager 클래스의 속성과 메서드를 이용.
-네트워크 상태 알아내기
-네트워크 연결 여부 알아내기
-WIFI 연결 상태 변경하기
-웹 서버 이미지 가져오기
-원격파일 내용읽기
-JSON 데이터 읽기
sample source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="network state" />
</LinearLayout>
sample source
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text);
text.setText(getNetworkState());
}
public String getNetworkState() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
String state = "";
Log.d("tag", "type : " + networkInfo.getType());
Log.d("tag", "subtype : " + networkInfo.getSubtype());
Log.d("tag", "subtypeName : " + networkInfo.getSubtypeName());
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
state = networkInfo.getState().toString();
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
state = networkInfo.getDetailedState().toString();
}
return state;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
sample source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NetWorkConnectState" />
<TextView
android:id="@+id/state"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
sample source
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean state = isNetworkAvailable(this);
String stateStr;
if (state) {
stateStr = "ConntectStateGood";
} else {
stateStr = "ConnectStateBAD";
}
TextView stateText = (TextView) findViewById(R.id.state);
stateText.setText(stateStr);
}
public static boolean isNetworkAvailable(Context context) {
boolean available = false;
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo(); // 네트워크 정보를 반환
if (info != null && info.isAvailable()) {
available = true;
}
return available;
}
WIFI 연결상태에 대한 제어는 WifiManager 클래스를 활용
sample source
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
changeWifi();
}
private void changeWifi() {
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wi = wifiMgr.getConnectionInfo();
toStringInfo(wi);
if (wifiMgr.isWifiEnabled()) {
wifiMgr.setWifiEnabled(false);
} else {
wifiMgr.setWifiEnabled(true);
}
toStringInfo(wi);
}
private void toStringInfo(WifiInfo wi) {
Log.d("tag", "getIpAddress : " + wi.getIpAddress());
Log.d("tag", "getMacAddress : " + wi.getMacAddress());
Log.d("tag", "getNetworkId : " + wi.getNetworkId());
Log.d("tag", "toString : " + wi.toString());
}
WIFI 변경에 대한 제어를 하기위한 권한 설정
sample source
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
원격지에 커넥션을 하기 위해서는 URLConnection 클래스가 사용됨
*위에서 이야기대로 네트워크작업 처럼 지연이 발생할 수 있는 작업은 UI 메인스레드에서 수행할 수 없음(AsyncTask 사용)
*AsyncTask - 자바에서의 쓰레드 처리 방법은 해당 API를 이용하는 사용자 측면에서 직관적이지 않은 형태를 가지고 있음
*위 비동기 작업을 편하게 해주기 위한 일종의 랩핑 클래스
*비동기 작업을 체계적으로 해주기 위해 다음과 같이 구성됨
*3개의 제네릭 타입을 제공Param.Progress.Result (이 시점에서 제네릭타입이란 실행 시점에 데이터 타입을 지정할 수 있음을 의미)
sample source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
sample source
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image1);
new ImageLoadingTask()
.execute("/imgs/ui/main/gurubee.jpg");
}
private Bitmap getRemoteImage(final URL url) {
Bitmap bitmap = null;
try {
URLConnection conn = url.openConnection();
conn.connect();
//이미지를 가지고 와서 decodeStream() 메소드로 Bitmap 이미지 생성
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream());
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private class ImageLoadingTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... strs) {
URL url = null;
try {
url = new URL(strs[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bitmap = getRemoteImage(url);
return bitmap;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
sample source
<uses-permission android:name="android.permission.INTERNET" />
메인스레드 정책 우회방법(AsyncTask 사용안함)
sample source
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
imageView = (ImageView) findViewById(R.id.image1);
...
원격지 *.html 읽기
HttpClient 는 HTTP 요청을 처리 할 수 있는 클래스 //HTTP 연결 인증 쿠키 작업 처리 가능
sample source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/viewarea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:height="300dp"
android:scrollbars="vertical" />
<Button
android:id="@+id/geturl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Get Url"
android:width="100dp" />
</LinearLayout>
sample source
...
@Override
public void onClick(View v) {
new RssLoadingTask()
.execute("/");
}
...
public String getStringFromUrl(String url)
throws UnsupportedEncodingException {
//입력스트림을 UTF-8로 읽음 -> 라인단위로 읽기 위해 BufferedReader 사용
BufferedReader br = new BufferedReader(new InputStreamReader(
getInputStreamFromUrl(url), "UTF-8"));
StringBuffer sb = new StringBuffer();
try {
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static InputStream getInputStreamFromUrl(String url) {
InputStream contentStream = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch (Exception e) {
e.printStackTrace();
}
return contentStream;
}
private class RssLoadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strs) {
String s = null;
try {
s = getStringFromUrl(strs[0]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
protected void onPostExecute(String result) {
text.setText(result);
}
}
sample source
<uses-permission android:name="android.permission.INTERNET" />
sample source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
sample source
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text);
new JsonLoadingTask().execute();
}
public String getJsonText() {
StringBuffer sb = new StringBuffer();
try {
String line = getStringFromUrl("http://192.168.110.1:8080/ewhaDemo/demo-xrf/20130419/data.json");
JSONObject object = new JSONObject(line);
sb.append("이름:").append(object.getString("이름")).append("\n");
sb.append("나이:").append(object.getInt("나이")).append("\n");
sb.append("성별:").append(object.getString("성별")).append("\n");
sb.append("결혼:").append(object.getBoolean("결혼")).append("\n");
sb.append("취미:");
JSONArray hobbyArray = new JSONArray(object.getString("취미"));
for (int i = 0; i < hobbyArray.length(); i++) {
sb.append(hobbyArray.getString(i)).append(",");
}
sb.append("\n");
sb.append("주소:").append(object.getString("주소")).append("\n");
sb.append("가족:");
JSONObject familyObject = new JSONObject(object.getString("가족"));
sb.append(familyObject.getString("아버지")).append(",");
sb.append(familyObject.getString("어머니"));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public String getStringFromUrl(String url)
throws UnsupportedEncodingException {
BufferedReader br = new BufferedReader(new InputStreamReader(
getInputStreamFromUrl(url), "utf-8"));
StringBuffer sb = new StringBuffer();
try {
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static InputStream getInputStreamFromUrl(String url) {
InputStream contentStream = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch (Exception e) {
e.printStackTrace();
}
return contentStream;
}
private class JsonLoadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strs) {
return getJsonText();
}
protected void onPostExecute(String result) {
text.setText(result);
}
}
sample source
<uses-permission android:name="android.permission.INTERNET" />